//
//  ServiceEvaluationTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/10.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "ServiceEvaluationTabVC.h"
#import "ServiceEvaluationTitleCell.h"
#import "ServiceEvaluationScopeCell.h"
#import "ServiceEvaluationContentCell.h"
#import "WriteRequirementTitleCell.h"
#import "CustomePickerImageVC.h"
#import "TZImagePickerController.h"
#import "ButtonCell.h"
#import "ServiceModel.h"
@interface ServiceEvaluationTabVC ()<ServiceEvaluationContentCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,ButtonCellDelegate,ServiceEvaluationScopeCellDelegate>
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) NSString *content;
@property(nonatomic,strong) NSString *images;
@property(nonatomic,strong) NSString *scope;
@property(nonatomic,strong) NSString *ishidden;
@end
static NSString *identifierTitle = @"title";
static NSString *identifierTitleCell = @"titleCell";
static NSString *identifierScopeCell = @"scopeCell";
static NSString *identifierContentCell = @"contentCell";
static NSString *identifierButton = @"buttonCell";
@implementation ServiceEvaluationTabVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"服务评价";
    self.manager = [AFHTTPSessionManager manager];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceEvaluationTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitleCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceEvaluationScopeCell" bundle:nil] forCellReuseIdentifier:identifierScopeCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceEvaluationContentCell" bundle:nil] forCellReuseIdentifier:identifierContentCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitle];
    [self.tableView registerNib:[UINib nibWithNibName:@"ButtonCell" bundle:nil] forCellReuseIdentifier:identifierButton];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0||section == 3) {
        return 1;
    }else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.section == 0) {
        ServiceEvaluationTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitleCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.serviceMode = self.model;
        return cell;
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.textLabel.text = @"服务总体评分";
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.detailTextLabel.text = @"";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            ServiceEvaluationScopeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierScopeCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            return cell;
        }
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.textLabel.text = @"服务整体评价";
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.detailTextLabel.text = @"";
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            ServiceEvaluationContentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierContentCell forIndexPath:indexPath];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
    }else {
        ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierButton forIndexPath:indexPath];
        [cell.btn setTitle:@"发布评价" forState:UIControlStateNormal];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 20;
        }else {
            return 40;
        }
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
           return 50;
        }else {
           return 400;
        }
    }else {
        return 200;
    }
}
#pragma mark-代理:发布
- (void)buttonCell:(ButtonCell *)buttonCell withClickBtn:(UIButton *)clickBtn
{
        self.urlString = [NSString stringWithFormat:@"%@/associationEvaluate/save",kUrl];
        NSString *aid = [NSString stringWithFormat:@"%ld",self.model.id];
        XLog(@"content:%@",self.content);
        XLog(@"scope:%@",self.scope);
        XLog(@"images:%@",self.images);
        XLog(@"ishidden:%@",self.ishidden);
        if (self.scope.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请打分"];
        }else  if (self.content.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请填写服务评价"];
        }else {
            self.dict = @{
                          @"uid":[UserDefaultsHelper readUid],
                          @"aid":aid,
                          @"content":self.content,
                          @"scope":self.scope,
                          @"images":self.images,
                          @"ishidden":self.ishidden,
                          @"rid":[NumberSwitchString numberSwitchString:self.model.rid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                XLog(@"responseObject:%@",responseObject);
                /**
                 date = "<null>";
                 message = "\U8bc4\U4ef7\U6210\U529f";
                 status = 200;
                 */
                NSString *messgae = [responseObject objectForKey:@"message"];
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:messgae];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (self.returnValueBlock) {
                        self.returnValueBlock(1);
                    };
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }
}
#pragma mark-代理:服务整体评价
- (void)serviceEvaluationContentCell:(ServiceEvaluationContentCell *)serviceEvaluationContentCell withAddIVBtn:(UIButton *)addIVBtn withTextView:(UITextView *)textView withSelect:(NSInteger)select
{
    self.content = textView.text;
    self.ishidden = [NSString stringWithFormat:@"%ld",select];
}
#pragma mark-代理:打分
- (void)serviceEvaluationScopeCell:(ServiceEvaluationScopeCell *)serviceEvaluationScopeCell withScope:(NSInteger)scope
{
    self.scope = [NSString stringWithFormat:@"%ld",scope];
}
#pragma mark-代理:上传照片
-(void)serviceEvaluationContentCell:(ServiceEvaluationContentCell *)serviceEvaluationContentCell withAddIVBtn:(UIButton *)addIVBtn 
{
    //打开照相机和图片
    UIAlertController *sheetControler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    CustomePickerImageVC *picker = [[CustomePickerImageVC alloc]init];
    
    picker.edgesForExtendedLayout =  UIRectEdgeNone;
    picker.automaticallyAdjustsScrollViewInsets = NO;
    
    picker.allowsEditing = YES;
    
    picker.delegate = self;
    sheetControler.popoverPresentationController.sourceView = self.view;
    sheetControler.popoverPresentationController.sourceRect = self.view.frame;
//    UIAlertAction *paizhao = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self takePhoto];
//        //先push一个控制器(在这个控制器里面可以编辑图片)
//
//        [self presentViewController:picker animated:YES completion:nil];
//    }];
//    UIAlertAction *xiangce = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
//    }];
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        //XLog(@"cancel");
//    }];
//    [sheetControler addAction:paizhao];
//    [sheetControler addAction:xiangce];
//    [sheetControler addAction:cancel];
    [self presentViewController:sheetControler animated:YES completion:nil] ;
}
- (void)pushTZImagePickerController {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:2];
    ServiceEvaluationContentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    // imagePickerVc.navigationBar.translucent = NO;
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    //    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    //    imagePickerVc.allowTakePicture = self.showTakePhotoBtnSwitch.isOn; // 在内部显示拍照按钮
    //    imagePickerVc.allowTakeVideo = self.showTakeVideoBtnSwitch.isOn;   // 在内部显示拍视频按
    //    imagePickerVc.videoMaximumDuration = 10; // 视频最大拍摄时间
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    
    // imagePickerVc.photoWidth = 1000;
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    /*
     [imagePickerVc setAssetCellDidSetModelBlock:^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
     cell.contentView.clipsToBounds = YES;
     cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
     }];
     */
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    //    imagePickerVc.allowPickingVideo = self.allowPickingVideoSwitch.isOn;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    // 设置竖屏下的裁剪尺寸
    //    NSInteger left = 30;
    //    NSInteger widthHeight = kVWidth - 2 * left;
    //    NSInteger top = (kVWidth - widthHeight) / 2;
    //    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    
    
    // 设置首选语言 / Set preferred language
    // imagePickerVc.preferredLanguage = @"zh-Hans";
    
    // 设置languageBundle以使用其它语言 / Set languageBundle to use other language
    // imagePickerVc.languageBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"tz-ru" ofType:@"lproj"]];
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        XLog(@"photos:%@",photos);
        /**
         2018-12-06 16:07:48.463518+0800 BusinessMarket[789:89872] photos:(
         "<UIImage: 0x2829bd340> size {750, 1206} orientation 0 scale 1.000000"
         )
         */
        UIImage *image = photos[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        [cell.selectIVBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        //选择回调
        [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            //二进制文件，接口key值，文件路径，图片格式
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            float update = uploadProgress.fractionCompleted*100;
            XLog(@"%f",update);
            XLog(@"%.f%%",update);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
                
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *stringImg = [responseObject mj_JSONString];
            NSDictionary *dict = [stringImg mj_JSONObject];
            XLog(@"stringImg:%@",stringImg);
            self.images = [dict objectForKey:@"path"];
            [WSProgressHUD dismiss];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    // 提前定位
    __weak typeof(self) weakSelf = self;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerVc = [[UIImagePickerController alloc] init];
        imagePickerVc.delegate = self;
        imagePickerVc.sourceType = sourceType;
        
        //        NSMutableArray *mediaTypes = [NSMutableArray array];
        //        if (self.showTakePhotoBtnSwitch.isOn) {
        //            [mediaTypes addObject:(NSString *)kUTTypeImage];
        //        }
        //        if (mediaTypes.count) {
        //            _imagePickerVc.mediaTypes = mediaTypes;
        //        }
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    } else {
        //        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:2];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    ServiceEvaluationContentCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    [cell.selectIVBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    //选择回调
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        float update = uploadProgress.fractionCompleted*100;
        XLog(@"%f",update);
        XLog(@"%.f%%",update);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
            
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSString *stringImg = [responseObject mj_JSONString];
        NSDictionary *dict = [stringImg mj_JSONObject];
        XLog(@"stringImg:%@",stringImg);
        self.images = [dict objectForKey:@"path"];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}
@end
